import {getSDRoot,createFile,writeTxtFile,clearTxtFile,gps2m,getDirection} from "@/utils/njs-io.js"
import {getFormatDate} from "@/utils/util.js"
import store from "@/store"
import configs from '@/config'


// 获得sd卡根目录
let sdRoot = null;
function xcInit(){
	sdRoot = getSDRoot();
	console.log(JSON.stringify(sdRoot));
	createFile(sdRoot,'track.txt');
	if(sdRoot != null){
		sendlocation();
		setInterval(sendPostlocationFile, 5*60*1000);
	}
}


var iLat,iLon,imei;
var interval = null;
function sendlocation() {
	interval = plus.geolocation.watchPosition(function(p) { //无法控制巡查时间间隔
		var x = p.coords.longitude;
		var y = p.coords.latitude;
		var accuracy = p.coords.accuracy;
		var altitude = p.coords.altitude;
		var desc = '',heading = '',speed = 0,mileage = 0;//地址、方向、速度、里程
		if(x < 0 || x > 180 || y < 0 || y > 180){
			return;
		}
		if(x == 5e-324 || y == 5e-324){
			return;
		}
		//获取地址
		if(p.address != null)
			desc = p.address.city + p.address.district + p.address.street;
		//获取方向
		if(p.coords.heading == null || p.coords.heading == 0 || p.coords.heading == 'NaN') {
			heading = "";
		} else {
			heading = getDirection(p.coords.heading);
		}
		//获取速度
		if(p.coords.speed == null || p.coords.speed == -1 || p.coords.speed == 'NaN' || p.coords.speed == 0) {
			speed = "0";
		} else {
			speed = p.coords.speed.toFixed(2);
		}
		if(iLat == null && iLon == null) {
			iLat = y;
			iLon = x;
			var con = x + ',' + y + ',' + getFormatDate() + ',' + imei + ',' + desc + ',,' + '0,0' + '\r\n';
			writeTxtFile(sdRoot+"/track.txt",con);
		} else {
			if( gps2m(iLat, iLon, y, x) != 0){
				mileage = gps2m(iLat, iLon, y, x).toFixed(2);
			} else {
				mileage = 0;
			}
			var con = x + ',' + y + ',' + getFormatDate() + ',' + imei + ',' + desc + ',' + heading + ',' + speed + ',' + mileage + '\r\n';
			writeTxtFile(sdRoot+"/track.txt",con);
			iLat = y;
			iLon = x;
		}
		console.log("获取定位："+JSON.stringify(p));
	}, function(e) {}, {
		provider: 'system',
		enableHighAccuracy: true,
		coordsType: 'wgs84',
		timeout: 4000,
		maximumAge: 11111
	});
};

function sendPostlocationFile(){
	console.log(getFormatDate()+"上传一次轨迹！");
	plus.geolocation.clearWatch(interval);  
	interval = null;  
	var files = [sdRoot+"/track.txt"];
	fileUpload(files, {userId: store.state.user.userInfo.id}).then(res=>{
		if(res && res.code == 200){
			console.log("上传轨迹成功！");
			clearTxtFile(files[0]);
		}
		sendlocation();
	});
}

function fileUpload(files, params){
	return new Promise((resolve,reject) => {
		files.forEach(file => {
			uni.uploadFile({
				url: configs.baseUrl+'/userTrall/uploadFile', //仅为示例，非真实的接口地址
				filePath: file,
				name: 'file',
				header:{
					"Authorization": "Bearer " + getToken()
				},
				formData: params,
				success: (uploadFileRes) => {
					if(typeof uploadFileRes.data == "string" ){
						uploadFileRes.data = JSON.parse(uploadFileRes.data)
					}
					resolve(uploadFileRes.data)
				},
				fail() {
					reject()
				}
			});
		});
		if(files.length==0)resolve();
	})
}

export {
	xcInit
}